import Layouts from '@/src/components/Layouts'
import React, { useState, useEffect } from 'react'
import { Card, Button, Table, message, Space, Modal, Form, Input, Select } from "antd"
import Paginations from '@/src/components/Pagination'
import http from '@/src/utils/https'
import BrokerSearch from '@/src/components/BrokerSearch'
const Broker = () => {
  //分页
  let [page, setPage] = useState(1);
  let [pagesize, SetpageSize] = useState(10);
  let [total, SetTotal] = useState(100);
  const handelpage = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "page")
    setPage(page)
    SetpageSize(pagesize)
  }
  const handelsize = (page: number, pagesize: number) => {
    // console.log(page, pagesize, "size")
    setPage(page)
    SetpageSize(pagesize)
  }
  //模糊搜素
  const handelsearch = (val: any) => {
    console.log(val, "search")
  }

  //获取数据
  let [brokerList, setBrokerList] = useState([] as any)
  let [brokerLists, setBrokerLists] = useState([] as any)
  let [timer, setTimer] = useState(false)
  // 获取数据
  const getbrokerList = (obj = {}) => {
    if (timer) return
    http.get("/broker", { params: obj }).then(res => {
      if (res.data.code == 200) {
        setBrokerList(res.data.data)
        SetTotal(res.data.data.length)
      }
      setTimer(false)
    })
    setTimer(true)
  }
  //初始化获取数据
  useEffect(() => {
    if (brokerList.length <= 0) {
      getbrokerList()
    }
  }, [])
  //处理渲染数据
  useEffect(() => {
    if (brokerList.length > 0) {
      let newList = brokerList.slice((page - 1) * pagesize, page * pagesize).map((item: any) => {
        item.key = item.id;
        return item
      })
      setBrokerLists(newList)
    }
  }, [brokerList, page, pagesize])



  //新增
  const handeladd = () => {
    setEdit(false)
    setIsModalOpen(true)
    form.setFieldValue("name", '')
    form.setFieldValue("tel", '')
    form.setFieldValue("company",'')
    form.setFieldValue("new_house", '')
    form.setFieldValue("second_hand_house", '')
    form.setFieldValue("renting", '')
    form.setFieldValue("state",'在职')
  }
  //编辑
  let [item, setitem] = useState({} as any)
  let [isedit, setEdit] = useState(true)
  const handeledit = (obj: any) => {
    setEdit(true)
    setIsModalOpen(true)
    setitem(obj)
    form.setFieldValue("name", obj.name)
    form.setFieldValue("tel", obj.tel)
    form.setFieldValue("company", obj.company)
    form.setFieldValue("new_house", obj.new_house)
    form.setFieldValue("second_hand_house", obj.second_hand_house)
    form.setFieldValue("renting", obj.renting)
    form.setFieldValue("state", obj.state)
  }

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const onFinish = async (values: any) => {
    console.log(values,"values")
    let obj = {} ;
    if(isedit){
      //编辑
      obj = {...item,...values}
      edits(obj)
    }else{
      //添加
      let content = {...values}
      let res = await http.put("/add/Broker",{content});
      console.log(res,"add")
      if(res.data.code==200){
        getbrokerList()
      }
    }


    setIsModalOpen(false);
  };
  const onFinishFailed = (errorInfo: any) => {
    //输入框为空时提示消息
    errorInfo.errorFields.map((item: any) => {
      message.warning(item.errors)
    })
  };
  const [form] = Form.useForm<{ username: string; address: string, price: string, city: string }>();
  const [isModalOpen, setIsModalOpen] = useState(false);
  //发送 编辑
  const edits = async (obj: any) => {
    let content = obj
    let res = await http.post("/set/BrokerStatus", { content });
    if (res.data.code == 200) {
      getbrokerList()
    }
  }
  //删除
  const handelete = async (id: any) => {
    let res = await http.delete("/del/broker", { params: { id } });
    if (res.data.code == 200) {
      getbrokerList()
    }
  }
  let columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 70
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 85
    },
    {
      title: '手机号',
      dataIndex: 'tel',
      key: 'tel',
      width: 110
    },
    {
      title: '公司',
      dataIndex: 'company',
      key: 'company',
      width: 110
    },
    {
      title: '新房',
      dataIndex: 'new_house',
      key: 'new_house',
      width: 70
    },
    {
      title: '二手房',
      dataIndex: 'second_hand_house',
      key: 'second_hand_house',
      width: 70
    }, {
      title: '租房',
      dataIndex: 'renting',
      key: 'renting',
      width: 70
    }, {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      width: 85
    }, {
      title: '操作',
      dataIndex: 'edit',
      key: 'edit',
      width: 200,
      render(_: any, item: any) {
        return (
          <Space>
            <Button type="link" onClick={() => handeledit(item)}>编辑</Button>
            <Button type="link" onClick={() => handelete(item.id)}>删除</Button>
            <Button type="link" disabled={item.state == "在职"} onClick={() => {
              let obj = { ...item }
              obj.state = "在职"
              edits(obj)
            }}>在职</Button>
            <Button type="link" disabled={item.state == "离职"} onClick={() => {
              let obj = { ...item }
              obj.state = "离职"
              edits(obj)
            }}>离职</Button>
          </Space>
        )
      }
    },
  ]
  return (
    <Layouts>
      <Card style={{ width: "100%" }} bordered={false}>
        <h2>经纪人管理</h2>
      </Card>
      <Card style={{ width: "100%" }} bordered={false}>
        <BrokerSearch handelsearch={handelsearch}></BrokerSearch>
      </Card>
      <Card style={{ width: "100%" }} bordered={false} extra={<Button type="primary" onClick={handeladd}>新增</Button>}>
        {/* 内容 */}
        {
          brokerLists.length > 0 &&
          <Table scroll={{ y: 540 }} style={{ height: 540, marginBottom: "10px" }} dataSource={brokerLists} columns={columns} pagination={false} />
        }
      </Card>
      {/* //分页 */}
      <Card bordered={false} style={{ width: '100%', position: "sticky", left: "0", bottom: "0", zIndex: "9", minWidth: "800px", borderTop: "1px solid #ccc" }}>
        <Paginations total={total} page={page} pagesize={pagesize} onpage={handelpage} onsize={handelsize}></Paginations>
      </Card>
      <Modal title="编辑" open={isModalOpen} footer={false} onCancel={handleCancel}>
        <Form
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          form={form}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="姓名"
            name="name"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="手机号"
            name="tel"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="公司"
            name="company"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="新房"
            name="new_house"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="二手房"
            name="second_hand_house"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="租房"
            name="renting"
            rules={[{ required: true, message: '哥们，输一下' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="状态" name='state' rules={[{ required: true, message: '哥们，选一下' }]}>
            <Select style={{ width: 150 }} allowClear options={[
              {
                value: '离职',
                label: '离职'
              },
              {
                value: '在职',
                label: '在职'
              }
            ]}></Select>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button type="default" onClick={handleCancel}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>



    </Layouts>
  )
}

export default Broker